<?php

class lexiang
{
    // protected $xml;
    // protected $head;

    // protected $channel_type = "WX";

    // protected $appid;

    // protected $IsvOrgId;


    // protected $provider_type;

    protected $password = "";  //证书密码
    protected $sign_no = "";  //证书序列号
    protected $signType = "RSA2";

    protected $baseUrl = 'https://efps.epaylinks.cn';
    protected $customer_code = '';  //商户号
    protected $callback_url = "";
    protected $client_ip = "";
    // protected $certKey = "";  //证书字符串
    protected $pfxFilePath = "";  //加签文件路径




    // protected $md5_key = "";
    // protected $publicKey = "";
    // protected $privateKey = "";
    // protected $merchant_id = "";




    public function __construct($setting)
    {
        $client_ip = '';

        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            // 检查是否存在客户端IP头
            $client_ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // 检查是否存在代理IP头
            $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED'])) {
            // 某些代理服务器使用X_FORWARDED头
            $client_ip = $_SERVER['HTTP_X_FORWARDED'];
        } elseif (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) {
            // 检查是否存在负载均衡器IP头
            $client_ip = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
            // 检查是否存在另一个代理IP头
            $client_ip = $_SERVER['HTTP_FORWARDED_FOR'];
        } elseif (!empty($_SERVER['HTTP_FORWARDED'])) {
            // 某些负载均衡器和代理服务器使用FORWARDED头
            $client_ip = $_SERVER['HTTP_FORWARDED'];
        } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
            // 如果以上头信息都不存在，则使用REMOTE_ADDR
            $client_ip = $_SERVER['REMOTE_ADDR'];
        }
        $this->client_ip = $client_ip;


        $this->callback_url = $setting['callback_url'] ?? "";
        $this->pfxFilePath = $setting['pfxFilePath'] ?? "";
        $this->password = $setting['password'] ?? "";
        $this->sign_no = $setting['sign_no'] ?? "";
        $this->customer_code = $setting['customer_code'] ?? "";
    }
    protected function sign($data)
    {
        $certs = array();
        // var_dump($this->password);
        // kx_user-rsa.pfx
        $pay_file = "/www/wwwroot/120.79.232.110/CzH5/payFile/" . $this->pfxFilePath;
        // var_dump(file_get_contents("/www/wwwroot/www.hfcz888.net/kx-official-system-php/payFile/private-rsa.key"));
        openssl_pkcs12_read(file_get_contents($pay_file), $certs, $this->password); //其中password为你的证书密码

        ($certs) or die('请检查RSA私钥配置');

        openssl_sign($data, $sign, $certs['pkey'], OPENSSL_ALGO_SHA256);

        $sign = base64_encode($sign);
        return $sign;
    }
    // 提交支付
    public function submitOrder($data)
    {
        $orderInfo['Id'] = $data['OutTradeNo'];
        $orderInfo['businessType'] = '100002';
        $orderInfo['goodsList'] = array(array(
            // 'name' => $data['merchant_name'],
            'name' =>  $data['OutTradeNo'],

            'number' => 'one',
            'amount' => $data['TotalAmount']
        ));
        $order = [
            // 'service' => 'pay.weixin.jspay',
            'version' => '3.0',
            'outTradeNo'     => $data['OutTradeNo'],
            'customerCode' => $this->customer_code,
            'appId' => $data['SubAppId'],
            'openId' => $data['OpenId'],
            'clientIp' => $this->client_ip,
            // 'clientIp' => $this->client_ip,
            "orderInfo" => $orderInfo,
            'payAmount'        => $data['TotalAmount'], // 单位：分
            'payCurrency' => 'CNY',
            'payMethod' => 35,
            // 1：公众号支付
            // 35：小程序支付
            // 默认 1
            'notifyUrl' => $data['NotifyUrl'] ?? $this->callback_url,
            "transactionStartTime" => date('YmdHis'),
            "areaInfo" => "440307",  //龙岗区
            'nonceStr' => $this->getRandomString(),

        ];
        $sign = $this->sign(json_encode($order));

        $file_name = $_SERVER['DOCUMENT_ROOT'] . "/../api_resource/logs/" . date('Ymd') . "_pay.log";

        file_put_contents($file_name, date('Y-m-d H:i:s') . "--------lexiang支付签名：" . $sign . ",请求报文---------", FILE_APPEND);
        file_put_contents($file_name, "\r\n", FILE_APPEND);
        file_put_contents($file_name, json_encode($order), FILE_APPEND);
        file_put_contents($file_name, "\r\n", FILE_APPEND);


        $request = $this->http_post_json($this->baseUrl . "/api/txs/pay/WxJSAPIPayment", json_encode($order), $sign);

        file_put_contents($file_name, date('Y-m-d H:i:s') . "--------lexiang支付响应报文：---------", FILE_APPEND);
        file_put_contents($file_name, "\r\n", FILE_APPEND);
        file_put_contents($file_name, json_encode($request), FILE_APPEND);
        file_put_contents($file_name, "\r\n", FILE_APPEND);

        if ($request && $request[0] == 200) {
            // echo '<br>' . '获取到的参数：';
            $res_arr = json_decode($request[1], true);

            if ($res_arr['returnCode'] == "000") {
                $json = $res_arr['wxJsapiParam'];
                $json['timestamp'] = $json['timeStamp'];
                return array('status' => 1, 'payInfo' => $json);
            } else {
                return array('status' => 0, 'msg' => $res_arr['returnMsg']);
            }

            // return $request[1];
        } else {
            // print_r($request);
            $res_arr = json_decode($request[1], true);

            // file_put_contents($file_name, date('Y-m-d H:i:s') . "--------lexiang支付响应报文：---------", FILE_APPEND);
            // file_put_contents($file_name, "\r\n", FILE_APPEND);
            // file_put_contents($file_name, json_encode($res_arr), FILE_APPEND);
            // file_put_contents($file_name, "\r\n", FILE_APPEND);
            return array('status' => 0, 'msg' => $res_arr['returnMsg']);
        }


        // if ($response_arr['status'] == 0) {
        //     $json = json_decode($response_arr['pay_info'], true);
        //     // 处理时间 timeStamp
        //     $json['timestamp'] = $json['timeStamp'];
        //     return array('status' => 1, 'payInfo' => $json);
        // } else {
        //     if (isset($response_arr['status'])) {
        //         return ['status' => 0, 'msg' => "下单失败:" . $response_arr['message']];
        //     }
        // }
    }

    // 回调
    public function notifyOrder($params)
    {

        // {"amount":100,"payTime":"20240406162138","openId":"oWSGp0XBLLPJaNM0Q2r_T_HRrdYI","transactionNo":"32202404066436235560392","cashAmount":100,"customerCode":"562596004446976","payState":"00","channelOrder":"4200002203202404063759295320","nonceStr":"41128b93ec2044dc92e101d71a47bdda","procedureFee":0,"couponAmount":0,"payerInfo":{"cardType":"D","fundChannel":"OTHERS"},"outTradeNo":"2024040616213324639","subOpenId":"oeC9r5_-B9okm2tDThPnSD-YaHL8","payerAmount":100}

        $resData = [
            'code' => 200,
            "data" => [],
            "msg" => "",
            "resp" => 'fail'
        ];
        // $sign = $this->getSgin($params);
        // if ($sign != $params['sign']) {
        //     $resData['code'] = 500;
        //     $resData['msg'] = "签名不匹配:sign" . $sign;
        //     return $resData;
        // }
        if ($params['payState'] == "00") {
            $resData["data"] = [
                "order_sn" =>  $params['outTradeNo'],
                "pay_order_sn" => $params['channelOrder']
            ];
            $resData["resp"] = [
                "returnCode" => "000"
            ];
            return $resData;
        } else {
            $resData = [
                'code' => 500,
                "data" => [],
                "msg" => "订单未支付",
                "resp" => [
                    "returnCode" => "000"
                ]
            ];
            return $resData;
        }
    }
    public function refund($order_sn, $refund_order_sn, $refund_price, $remark)
    {
        $data = [
            "customerCode" => $this->customer_code,
            "outRefundNo" => $refund_order_sn,
            "outTradeNo" => $order_sn,
            "refundAmount" => $refund_price,
            "amount" => $refund_price,
            "nonceStr" => $this->getRandomString()
        ];
        $sign = $this->sign(json_encode($data));
        $file_name = $_SERVER['DOCUMENT_ROOT'] . "/../api_resource/logs/" . date('Ymd') . "_pay.log";
        file_put_contents($file_name, date('Y-m-d H:i:s') . "--------lexiang退款签名：" . $sign . ",请求报文---------", FILE_APPEND);
        file_put_contents($file_name, "\r\n", FILE_APPEND);
        file_put_contents($file_name, json_encode($data), FILE_APPEND);
        file_put_contents($file_name, "\r\n", FILE_APPEND);

        $request = $this->http_post_json($this->baseUrl . "/api/txs/pay/Refund/V2", json_encode($data), $sign);

        file_put_contents($file_name, date('Y-m-d H:i:s') . "--------lexiang退款响应报文：---------", FILE_APPEND);
        file_put_contents($file_name, "\r\n", FILE_APPEND);
        file_put_contents($file_name, json_encode($request), FILE_APPEND);
        file_put_contents($file_name, "\r\n", FILE_APPEND);


        $data = [
            "code" => 500,
            "data" => [],
            "msg" =>  ''
        ];
        if ($request && $request[0] == 200) {
            $return_data = json_decode($request[1], true);
            if ($return_data['returnCode'] == "0000") {
                $data['code'] = 200;
                $data['msg'] = $return_data['returnMsg'];
                return $data;
            } else {
                if (isset($return_data['returnCode'])) {
                    $data['code'] = 500;
                    $data['msg'] = "退款失败，原因：" . $return_data['returnMsg'];
                    return $data;
                }
            }
        }
    }

    public function getRandomString()
    {
        // mt_srand((float)microtime() * 10000); //optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        // $hyphen = chr(45); // "-"
        $uuid = substr($charid, 0, 8)
            . substr($charid, 8, 4)
            . substr($charid, 12, 4)
            . substr($charid, 16, 4)
            . substr($charid, 20, 12);
        return $uuid;
    }
    protected function http_post_json($url, $jsonStr, $sign)
    {
        $ch = curl_init();
        $headers = array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($jsonStr),
            'x-efps-sign-no:' . $this->sign_no,
            'x-efps-sign-type:SHA256withRSA',
            'x-efps-sign:' . $sign,
            'x-efps-timestamp:' . date('YmdHis'),
        );
        $file_name = $_SERVER['DOCUMENT_ROOT'] . "/../api_resource/logs/" . date('Ymd') . "_pay.log";
        file_put_contents($file_name, date('Y-m-d H:i:s') . "--------lexiang请求头签名：" . $sign . ",请求报文---------", FILE_APPEND);
        file_put_contents($file_name, "\r\n", FILE_APPEND);
        file_put_contents($file_name, json_encode($headers), FILE_APPEND);
        file_put_contents($file_name, "\r\n", FILE_APPEND);


        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查        
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        //curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($ch);

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        return array($httpCode, $response);
    }
}
